<template>
  <div class="industry-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>行业管理</span>
          <el-button type="primary" @click="handleCreate">新增行业</el-button>
        </div>
      </template>

      <el-table :data="industries" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="行业名称" />
        <el-table-column prop="code" label="行业编码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑行业' : '新增行业'" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="行业名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入行业名称" />
        </el-form-item>
        <el-form-item label="行业编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入行业编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const industries = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

const form = reactive({
  id: undefined,
  name: '',
  code: '',
  description: '',
  sort: 0,
})

const rules = {
  name: [{ required: true, message: '请输入行业名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入行业编码', trigger: 'blur' }],
}

// 获取行业列表
const fetchIndustries = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/industries')
    industries.value = response.data
  } catch (error) {
    ElMessage.error('获取行业列表失败')
  } finally {
    loading.value = false
  }
}

// 新增行业
const handleCreate = () => {
  isEdit.value = false
  Object.assign(form, {
    id: undefined,
    name: '',
    code: '',
    description: '',
    sort: 0,
  })
  dialogVisible.value = true
}

// 编辑行业
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除行业
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该行业吗？', '提示', {
      type: 'warning',
    })
    await axios.delete(`/api/industries/${row.id}`)
    // 记录删除日志
    await axios.post('/api/logs', {
      action: 'DELETE_INDUSTRY',
      description: `删除行业：${row.name}`,
    })
    ElMessage.success('删除行业成功')
    fetchIndustries()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除行业失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    if (isEdit.value) {
      await axios.put(`/api/industries/${form.id}`, form)
      // 记录更新日志
      await axios.post('/api/logs', {
        action: 'UPDATE_INDUSTRY',
        description: `更新行业：${form.name}`,
      })
      ElMessage.success('更新行业成功')
    } else {
      await axios.post('/api/industries', form)
      // 记录创建日志
      await axios.post('/api/logs', {
        action: 'CREATE_INDUSTRY',
        description: `创建行业：${form.name}`,
      })
      ElMessage.success('创建行业成功')
    }
    dialogVisible.value = false
    fetchIndustries()
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error(isEdit.value ? '更新行业失败' : '创建行业失败')
  }
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问行业管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

onMounted(() => {
  fetchIndustries()
  recordPageAccess()
})
</script>

<style scoped>
.industry-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
